let fs = require('fs')
const { exec, spawn } = require('child_process');
const { resolve } = require('path')
const path = require('path')
const {createGzip} = require('zlib');
const { pipeline } = require('stream');
const {cmdRun} = require('./utils')
const {
    basePath,
    sourceDir,
    sourceDirJS,
    targetArr
} = require('./config')

// 返回运行文件所在的目录
console.log('__dirname : ' + __dirname)
// __dirname : /Desktop

// 当前命令所在的目录
console.log('resolve   : ' + resolve('./'))
// resolve   : /workspace

// 当前命令所在的目录
console.log('cwd       : ' + process.cwd())
// cwd       : /workspace

// 当前文件的上级目录
console.log('../       : ' + resolve(__dirname, 'output/*'))//

// const basePath = resolve(__dirname, '../output')
// const sourceDir = resolve(__dirname, '../dist')
// const sourceDirJS = resolve(sourceDir, 'js')
// const targetArr = [
//   {
//     name: 'production',
//     baseTargetPath: resolve(basePath, 'production'),
//     replaceArr: [
//       // {
//       //   old: 'http://xzbadmin.yhemall.com:18080',
//       //   new: 'http://121.199.174.232:18080',
//       // },
//       // {
//       //   old: 'ws://xzbadmin.yhemall.com:18080/api/im/lili/webSocket',
//       //   new: 'ws://121.199.174.232:18080/api/im/lili/webSocket',
//       // },
//     ]
//   },
//   {
//     name: 'test',
//     baseTargetPath: resolve(basePath, 'test'),
//     replaceArr: [
//       {
//         old: 'http://xzbadmin.yhemall.com:18080',
//         new: 'http://121.199.174.232:18080',
//       },
//       {
//         old: 'ws://xzbadmin.yhemall.com:18080/api/im/lili/webSocket',
//         new: 'ws://121.199.174.232:18080/api/im/lili/webSocket',
//       },
//     ]
//   },
//   {
//     name: 'localhost',
//     baseTargetPath: resolve(basePath, 'localhost'),
//     replaceArr: [
//       {
//         old: 'http://xzbadmin.yhemall.com:18080',
//         new: 'http://localhost:18080',
//       },
//       {
//         old: 'ws://xzbadmin.yhemall.com:18080/api/im/lili/webSocket',
//         new: 'ws://localhost:18080/api/im/lili/webSocket',
//       },
//     ]
//   },
// ]

// const cmdRun = (command)=>{
//   return new Promise((resolve, rejects)=>{
//       if(command) {
//         console.log(`开始执行：${command}`)
//         const execRuner = exec(command,{ encoding: "buffer" }, function (error, stdout, stderr) {
//             if (error) {
//               console.log(`执行的错误: ${error}`)
//               return;
//             }else if (stderr) {
//               console.log(`标准错误输出: ${stderr}`)
//             }
//             console.log(`命令的输出结果：\n${stdout}`)
//           });
//         execRuner.on('exit', function (code) {
//           console.log(`命令${command} 执行结束： ${code}`)
//           resolve()
//         })
//       }
//   })
// }

function gzipFile (sourcePath){
  return new Promise((resolve, reject)=>{
    let targetpath = sourcePath+'.gz'
    
    const gzip = createGzip();
    const rs = fs.createReadStream(sourcePath);
    const ws = fs.createWriteStream(targetpath);
    // pipeline(rs, gzip, ws, (err) => {
    //   if (err) {
    //       process.exitCode = 1;
    //   } else {
    //       // // 将文件名改回去
    //       // fs.renameSync(destPath, srcPath);
    //       // console.log('gz:' ,targetpath);
    //       console.log('文件替换完gzip成功: ', targetpath);
    //   }
    //   resolve()
    // });
    rs.pipe(gzip).pipe(ws);
    ws.on('finish', resolve);
    ws.on('error', reject);
    rs.on('error', reject);
    gzip.on('error', reject);
  })
}
async function gzipFileAsync(sourcePath) {
  const result = await gzipFile(sourcePath);
}

function handleFilerParse(curFilePath, targetFile) {
  if(targetFile.endsWith('.js')) {// 处理js
    const content = fs.readFileSync(curFilePath, 'utf8');
    targetArr.forEach(async item=>{
        const tasrgetFullPath = path.join(item.baseTargetPath, targetFile)
        let newContent = content
        item.replaceArr.forEach(rItem=>{
          if(content.indexOf(rItem.old) > -1) {
            console.log('文件替换: ', curFilePath , );
            console.log('文件替换: ', rItem.old , rItem.new);
            // console.log('rItem.old', rItem.old)rItem.new
            // console.log('content', content)
            newContent = newContent.replace(new RegExp(rItem.old, 'g'), rItem.new)//.replaceAll(rItem.old, rItem.new)
          }
        })
        if(newContent !== content) {
          fs.writeFileSync(tasrgetFullPath, newContent)
          console.log('文件替换成功: ', tasrgetFullPath);
          await gzipFileAsync(tasrgetFullPath);
          console.log('文件替换完gzip: ', tasrgetFullPath);
        }
    })
  }
}
function handleDirectory(source, target) {
  try {
    // if(target) {
    //   targetArr.forEach(item=>{
    //     let targetDirectoryPath = path.join(item.baseTargetPath, target)
    //     // console.log('targetDirectoryPath', targetDirectoryPath);
    //     fs.mkdirSync(targetDirectoryPath);
    //   })
    // }
    // 读取文件夹中的所有文件/文件夹名
    const files = fs.readdirSync(source);
    // 遍历文件列表
    files.forEach(file => {
      const curFilePath = path.join(source, file)
      const targetFile = path.join(target, file)
      const stats = fs.statSync(curFilePath);
      if (stats.isFile()) {
        handleFilerParse(curFilePath, targetFile)
        // console.log('该路径是一个文件');
      } else if (stats.isDirectory()) {
        // console.log('该路径是一个文件夹');
        handleDirectory(curFilePath, targetFile)
      } else {
        console.log('该路径既不是文件也不是文件夹:' + curFilePath);
      }
      // console.log(file); // 输出文件名
      // 如果需要读取文件内容，可以使用fs.readFileSync
      // const filePath = path.join(source, file);
      // console.log(filePath)
      // const content = fs.readFileSync(filePath, 'utf8');
      // console.log(content); // 输出文件内容
    });
  } catch (error) {
    console.error('Error reading the folder:', error);
  }
}
function copySync(source) {
  // console.log('source', source);
  const stats = fs.statSync(source);
  if (stats.isFile()) {
    // console.log('该路径是一个文件');
  } else if (stats.isDirectory()) {
    // console.log('该路径是一个文件夹');
    handleDirectory(source, '')
  } else {
    // console.log('该路径既不是文件也不是文件夹');
  }
}
cmdRun(`yarn build`).then(res=>{
  cmdRun(`IF EXIST  "${basePath}" rmdir /Q /s "${basePath}"`).then(res=>{
    cmdRun(`md "${basePath}"`).then(res=>{
      let index = 0
      const copyStaticFile = (item)=>{
        cmdRun(`md "${item.baseTargetPath}"`).then(res=>{
          cmdRun(`xcopy ${sourceDir} ${item.baseTargetPath} /E /I`).then(res=>{
            index++
            console.log('index', index);
            if(index < targetArr.length) {
              copyStaticFile(targetArr[index])
            }else{
              // copySync(sourceDir)
              handleDirectory(sourceDirJS, 'static/js')
              console.log('文件替换结束');
            }//
          })
        })
      }
      if(targetArr.length > 0) {
        copyStaticFile(targetArr[index])
      }
    })
  })
})